<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="/css/elementui/index.css">
    <link rel="stylesheet" href="/css/exam/css/style.css">
    <link rel="stylesheet" href="/iconfont/iconfont.css">
</head>

<body>
    <div id="app">
        <div class="p-30">
            {{ csrf_field() }}
            <el-row>
                <span class="icon iconfont icon-arrow_back"></span> <a
                    href="{{route('admin.warehouse.orderlistdata')}}">返 回</a> | 修改入库
            </el-row><br>
            <el-form :inline="true" :model="addReferWebForm" :rules="rules" ref="addReferWebForm" label-width="100px"
                class="demo-ruleForm">
                <el-row>
                        <el-form-item label="所属分类" prop="goods_id">
                            <el-cascader
                            	class="w-400px"
                            	:clearable="true"
                            	:options="goods"
                            	:props="props"
                            	v-model="addReferWebForm.goods_id"
                            	placeholder="请选择分类名称"
                            	clearable
                            	 ref='postSelectRef' 
                            	 @change='postValueChange($event)'
                            ></el-cascader> 
                        </el-form-item>

                        <el-form-item label="物资名称" prop="material_id">
                            <el-select v-model="addReferWebForm.material_id" placeholder="请选择物资名称">
                                <el-option v-for="item in goods_meteriallist" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                            <span class="icon iconfont icon-jiahaozhankai" @click="outerVisible = true"></span>
                        </el-form-item>

                        <el-form-item label="数&ensp;&ensp;量" prop="number" placeholder="数量">
                            <el-input v-model="addReferWebForm.number"></el-input>
                        </el-form-item>

                        <el-form-item label="单&ensp;&ensp;位" prop="unit" placeholder="单位">
                            <el-input v-model="addReferWebForm.unit"></el-input>
                        </el-form-item>

                        <el-form-item label="规&ensp;&ensp;格" placeholder="规格">
                            <el-input v-model="addReferWebForm.norms"></el-input>
                        </el-form-item>

                        <el-form-item label="备&ensp;&ensp;注" placeholder="备注">
                            <el-input v-model="addReferWebForm.remarks"></el-input>
                        </el-form-item>

                        <el-form-item label="所属单位" prop="checkcategory_id">
                            <el-select v-model="addReferWebForm.checkcategory_id" placeholder="请选择所属单位"
                                @change="ChangeHandler">
                                <el-option v-for="item in checkcategory" :key="item.id" :label="item.name"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="单位名称" prop="company_id">
                            <el-select v-model="addReferWebForm.company_id" filterable placeholder="请选择单位名称"
                                @change="ChangeCom">
                                <el-option v-for="item in comdata" :key="item.comName" :label="item.comName"
                                    :value="item.id">
                                </el-option>
                            </el-select>
                        </el-form-item>

                        <el-form-item label="具体位置" placeholder="请输入具体位置" prop="seat">
                            <el-input v-model="addReferWebForm.seat"></el-input>
                        </el-form-item>

                     <!--   <el-form-item label="图&ensp;&ensp;片">
                            <el-upload ref='upload' action="/admin/upload/uploadimg?_token={{ csrf_token() }}"
                                list-type="picture-card" :on-remove="handleRemove" :on-success="handleAvatarSuccess"
                                :on-preview="handlePictureCardPreview" :file-list="fileList">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisible">
                                <img width="100%" :src="dialogImageUrl" alt="">
                            </el-dialog>
                        </el-form-item>-->

                        <el-row>
                            <el-button @click="save('addReferWebForm')" type="primary" v-debounce>保&ensp;&ensp;存
                            </el-button>
                            <el-button @click="cancel('addReferWebForm')" type="danger">清&ensp;&ensp;除</el-button>
                        </el-row>
                </el-row>
            </el-form>
            <template>
                <h3 class="text-center">北宅街道应急物资入库单</h3>
                <el-table :data="allarr" border style="width: 100%" v-loading="loading">
                    <el-table-column  label="类&ensp;&ensp;别" width="100">
                      <template  slot-scope="scope"> 
						 <span v-if="scope.row.goods_id == item.id" v-for="item in goodsFlat" :key="item.id">
						   @{{item.name}}
						 </span>
                         <!-- <span v-if="scope.row.goods_id">@{{scope.row.goods_name}}</span> -->                  
                      </template> 
                    </el-table-column>
                    <el-table-column prop="material_id" label="物资名称" width="100">
                    <template  slot-scope="scope">
                        <span v-if="scope.row.material_id==item.id" v-for="item in materialList" :key="item.id">
                          @{{item.name}}
                       </span>                   
                    </template>		
                    </el-table-column>
                    <el-table-column label="数&ensp;&ensp;量" width="100">
                        <template slot-scope="scope">
                            <el-input v-model="scope.row.number" onKeyUp="value=value.replace(/^0|[^0-9]/g, '')">
                            </el-input>
                        </template>
                    </el-table-column>
                    <el-table-column prop="unit" label="单&ensp;&ensp;位" width="120"> </el-table-column>
                    <el-table-column prop="norms" label="规&ensp;&ensp;格" width="100"> </el-table-column>
                    <el-table-column prop="checkcategory_id" label="所属单位" width="">
                        <template slot-scope="scope">
                            <span v-if="scope.row.checkcategory_id==item.id" v-for="item in checkcategory"
                                :key="item.id">
                                @{{item.name}}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="company_id" label="单位名称" width="260" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <span v-if="scope.row.company_id==item.id" v-for="item in companys" :key="item.id">
                                @{{item.comName}}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="seat" label="具体位置" width="260" show-overflow-tooltip> </el-table-column>
                    <el-table-column prop="remarks" label="备&ensp;&ensp;注" width=""> </el-table-column>
                    <el-table-column fixed="right" label="操&ensp;&ensp;作" width="">
                        <template slot-scope="scope">
                            <el-button @click.native.prevent="deleteRow(scope.$index, allarr)" size="mini"
                                type="danger">
                                删&ensp;&ensp;除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <!-- <br><span style="font-size:15px;color:#606266">申请人</span>&nbsp;-->
                <!--<el-input v-model="applicant" placeholder="" style="width:200px"></el-input>-->

                <br><br>
                <el-row>
                    <el-button type="primary" @click="submitall"  v-debounce><a
                            style="display:block;color:#fff;text-decoration:none">确&ensp;&ensp;定</a></el-button>
                    <el-button @click="cancelall"><a>重&ensp;&ensp;置</a></el-button>
                </el-row>
            </template>

            <!--添加物资名称-->
            <el-dialog title="添加物资名称" :visible.sync="outerVisible">
                <el-form :model="addmForm" :rules="rules" ref="addmForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="物资分类" prop="goods_id">
                        <el-select v-model="addmForm.goods_id" placeholder="请选择分类">
                            <el-option v-for="item in goods" :key="item.id" :label="item.name" :value="item.id">
                            </el-option>
                        </el-select>
                        <span class="icon iconfont icon-jiahaozhankai" @click="innerVisible = true"></span>
                    </el-form-item>
                    <el-form-item label="物资属性" prop="attribute">
                        <el-radio v-model="addmForm.attribute" label="1">消耗品</el-radio>
                        <el-radio v-model="addmForm.attribute" label="2">固定资产</el-radio>
                    </el-form-item>
                    <el-form-item label="物资名称" prop="name">
                        <el-input v-model="addmForm.name"></el-input>
                    </el-form-item>
                    <el-form-item label="备&ensp;&ensp;注">
                        <el-input v-model="addmForm.remarks"></el-input>
                    </el-form-item>
                </el-form>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="outerVisible = false">取&ensp;&ensp;消</el-button>
                    <el-button type="primary" @click="saveMaterial('addmForm')"  v-debounce>确&ensp;&ensp;定</el-button>
                </span>
                <!--添加物资分类-->
                <el-dialog width="30%" title="添加物资分类" :visible.sync="innerVisible" append-to-body>
                    <el-form :model="addgForm" :rules="rules" ref="addgForm" label-width="100px" class="demo-ruleForm">
                        <el-form-item label="分类名称" prop="name">
                            <el-input v-model="addgForm.name"></el-input>
                        </el-form-item>
                        <el-form-item label="备&ensp;&ensp;注">
                            <el-input v-model="addgForm.remarks"></el-input>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="innerVisible = false">取&ensp;&ensp;消</el-button>
                        <el-button type="primary" @click="saveGoods('addgForm')" v-debounce>确&ensp;&ensp;定</el-button>
                    </span>
                </el-dialog>
            </el-dialog>


        </div>

    </div>
</body>
<script src="/css/exam/js/vue.js"></script>
<script src="/css/elementui/index.js"></script>
<script src="/css/exam/js/axios.min.js"></script>
<script src="/css/exam/js/common.js"></script>
<script>
const app = new Vue({
    el: '#app',
    data() {
        return {
            loading: false,
            id: '',
            addReferWebForm: {
                goods_id: '',
				goods_name:'',
                material_id: '',
                checkcategory_id: '',
                company_id: '',
                number: '',
                unit: '',
                norms: '',
                remarks: '',
                seat: '',
                img_url: '',
            },
            applicant: '',
            warehouse_type: '',
            allarr: [],
            uploadComplete: true, // 图片上传完成状态
            goods: [],
			goodsFlat:[],
			result:[],
            materialList: [],
			goods_meteriallist:[],
            get_warehouse_type: [],
            checkcategory: [],
            companys: [],

            fileList: [],
            dialogImageUrl: '',
            dialogVisible: false,

            warehouseOrderData: [],

            addmForm: {
                goods_id: '',
                attribute: '',
                name: '',
                remarks: '',
            },

            selval: '',
            selcomval: '',
            comdata: [],

            addgForm: {
                name: '',
                remarks: '',

            },
            outerVisible: false,
            innerVisible: false,
			
			  props: {
				value: 'id',
				label: 'name',
				children: 'children',
				checkStrictly: true,
			  },
			  CascaderLabel:'',
			  CascaderId:'',

            rules: {
                number: [{required: true,message: '请输入数字',trigger: 'blur'},
                     { pattern: /^([1-9]|[0-9]{0,16})$/, message: '请输入大于0的数字', trigger: 'blur' },
                ],
                goods_id: [{ type: 'array', required: true, message: '请选择', trigger: 'blur'},],
                material_id: [{ required: true,message: '请选择'},],

                unit: [{required: true,message: '请输入单位',trigger: 'blur'}],
                checkcategory_id: [{required: true,message: '请选择'}, ],
                company_id: [{required: true,message: '请选择'}, ],
                seat: [{required: true,message: '请输入具体位置',trigger: 'blur'}],
                attribute: [{required: true,message: '请选择'}, ],
                name: [{required: true,message: '请输入'}, ],
                applicant: [{required: true,message: '请选择'}, ],
            },
        }

    },
    created() {
        this.getUrlKey(),
            this.getone(),
            this.get(),
            this.getgoodsdata()

    },
    methods: {
        //获取当前浏览器地址url中的id
        getUrlKey() {
            var url = window.location.href; //获取当前url
            var dz_url = url.split('#')[0]; //获取#/之前的字符串
            //获取?之后的参数字符串
            if (dz_url.split('?')[1] != undefined) {
                var cs = dz_url.split('?')[1];
                var cs_arr = cs.split('&'); //参数字符串分割为数组
                var cs = {};
                for (var i = 0; i < cs_arr.length; i++) { //遍历数组，拿到json对象
                    cs[cs_arr[i].split('=')[0]] = cs_arr[i].split('=')[1]
                }
                this.id = cs.id;
                this.warehouse_type = cs.warehouse_type
                console.log(this.id)
            } else {
                this.id = ''
            };
        },
        // 获取下拉列表
        get() {
            axios.post('/admin/warehouseMaterials/referweb')
                .then(res => {
                    if (res.data.code == 200) {
                        this.materialList = res.data.data.materialList
                        this.get_warehouse_type = res.data.data.get_warehouse_type
                        this.checkcategory = res.data.data.checkcategory
                        this.companys = res.data.data.companys
                    }
                })
        },
        // 暂时保存在页面
        save(formName) {
			
          this.$refs[formName].validate((valid) => {
          if (valid) {   
			this.addReferWebForm.goods_id = this.CascaderId
			this.addReferWebForm.goods_name = this.CascaderLabel
            let data = Object.assign({},this.addReferWebForm);//Object.assign({},需要push的对象) 将需要放入数组的对象先深拷贝一份
            this.allarr.push(data) ;
			this.$refs.postSelectRef.$refs.panel.clearCheckedNodes(); 	
			this.$refs[formName].resetFields();
            // this.$refs.upload.clearFiles();             
            // this.dialogImageUrl = ''
            console.log(this.allarr,'allarr')
          } else {
            return false;
          }
        });
        },

        // 确定保存
        submitall(formName) {

            let pagram = {
                id: this.id,
                applicant: this.applicant,
                warehouse_type: this.warehouse_type,
                materials: this.allarr
            }
            axios.post('/admin/warehouseMaterials/warehouseMaterialsRefer', pagram)
                .then(res => {
                    if (res.data.code == 200) {
                        this.$message({
                            message: '保存成功',
                            type: 'success'
                        });
						window.location=document.referrer
                        this.allarr = [],
                            this.applicant = ''
                    } else {
                        this.$message.info("保存失败！")
                    }
                })

        },
        cancelall() {
            this.allarr = [],
                this.applicant = ''
        },
        // 回显数据
        getone() {
            if (this.id != '' || this.id != null) {
                this.loading = true
                let id = this.id
                axios.post('/admin/warehouseMaterials/referweb', {
                        id: id
                    })
                    .then(res => {
                        this.allarr = res.data.data.warehouseMaterials,
                        this.loading = false;
						console.log(this.allarr, 'this.allarr');
                    }).catch(error => {
                        console.log('请求失败：' + error);
                        this.loading = false;
                    })
            }
        },
        // 编辑、增加物资名称
        saveMaterial(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let addmForm = this.addmForm
                    axios.post('/admin/materialList/refer', addmForm)
                        .then(res => {
                            if (res.data.code == 200) {
                                this.getdata()
                                this.$message({
                                    message: '保存成功',
                                    type: 'success'
                                });
                                this.$refs[formName].resetFields();
                                this.outerVisible = false
                            } else {
                                this.$message.info("保存失败！")
                            }
                        })
                } else {
                    return false;
                }
            });
        },
        // 编辑、增加物资分类
        saveGoods(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let addgForm = this.addgForm
                    axios.post('/admin/goods/goodsdo', addgForm)
                        .then(res => {
                            if (res.data.code == 200) {
                                this.getgoodsdata()
                                this.$message({
                                    message: '保存成功',
                                    type: 'success'
                                });
                                this.$refs[formName].resetFields();
                                this.innerVisible = false
                            } else {
                                this.$message("保存失败！")
                            }
                        })
                } else {
                    return false;
                }
            });
        },
           //获取物资分类
            getgoodsdata() {  
                let vm = this   
                axios.post('/admin/goods/goods_all')
                .then(response =>{
                    vm.goods = response.data.data;
					 console.log(vm.goods,'goods');
					 vm.goodsFlat = this.flattenArray(vm.goods) //扁平获取物资id和name
					 console.log(vm.goodsFlat,'flat');
                }).catch(error =>{
                    console.log('请求失败：' + error);
                })
            },
			flattenArray(arr) { 
			  for (let i = 0; i < arr.length; i++) {
			    let obj=arr[i]
				let obj2={}
				obj2["id"]=obj.id
				obj2["name"]=obj.name
				this.result.push(obj2)
				if (Array.isArray(obj.children) && obj.children) {
					this.flattenArray(obj.children)
				}else{
					return
				}
			  }
			 return this.result;
			},
		//获取物资列表
		getdata() {    
		  this.loading = true  
		  let vm = this 
		  axios.post('/admin/materialList/list_data',{name:null,page:1,limit:5000})
		  .then(response =>{
		      vm.materialList = response.data.data.list;
		      vm.loading = false; 
		  }).catch(error =>{
		      console.log('请求失败：' + error);
		      vm.loading = false; 
		  })
		}, 

        cancel(formName) {
            this.$refs[formName].resetFields();
            this.dialogImageUrl = ''
        },

        // 图片上传成功
        handleAvatarSuccess(response, file, fileList) {
            this.uploadComplete = true;
            this.fileChange(fileList);
        },
        // 移除图片
        handleRemove(file, fileList) {
            this.fileChange(fileList);
            console.log(this.addReferWebForm.img_url)
        },
        // 设置img_url值
        fileChange(fileList) {
            let temp_str = '';
            if (fileList.length > 0) {
                for (let i = 0; i < fileList.length; i++) {
                    // 最终img_url的格式是所有已上传的图片的url拼接的字符串（逗号隔开）
                    temp_str = temp_str + fileList[i].response.data[0].url + ',';
                }
            }

            this.addReferWebForm.img_url = temp_str;
            console.log(temp_str)
        },
        // 图片预览
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url;
            this.dialogVisible = true;
        },


        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpg' || file.type === 'image/png' || file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG/PNG/JPEG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        // 删除列表行
        deleteRow(index, rows) {
            rows.splice(index, 1);
            console.log('#', this.allarr)
        },
        //点击所属单位，单位下拉修改
        ChangeHandler(val) {
            let vm = this
            vm.selval = val;
            console.log('##', vm.selval);
            axios.post('/admin/stock/company_all', {
                    checkcategory_id: vm.selval
                })
                .then(res => {
                    vm.comdata = res.data.data
                    vm.addReferWebForm.company_id = ''
                    vm.addReferWebForm.seat = ''
                    console.log(vm.comdata);
                }).catch(error => {
                    console.log('请求失败：' + error);
                    vm.loading = false;
                })

        },
        //点击单位下拉，地址出现
        ChangeCom(val) {
            let vm = this
            vm.selcomval = val
            vm.addReferWebForm.seat = ''

            vm.comdata.forEach(item => {
                if (item.id == vm.selcomval) {
                    vm.addReferWebForm.seat = item.address
                }
            })
            return vm.addReferWebForm.seat
        },
		postValueChange(value) {
			if(this.$refs["postSelectRef"].getCheckedNodes()[0]){
				let pathid = this.$refs["postSelectRef"].getCheckedNodes()[0].uid
				this.CascaderId = pathid + 1
				let pathlabel = this.$refs["postSelectRef"].getCheckedNodes()[0].pathLabels
				console.log(pathlabel,'eeeeee');
				this.CascaderLabel = pathlabel[pathlabel.length - 1]
			}
					
			//选择分类，物资名称跟着变化
			  axios.post('/admin/materialList/material_all',{goods_id:this.CascaderId})
			  .then(res =>{
				  this.addReferWebForm.material_id = null
				  this.goods_meteriallist = res.data.data				  
				  console.log(this.goods_meteriallist);
			  }).catch(error =>{
				  console.log('请求失败：' + error);
			  })
		},


    },
})
</script>
<style>
.el-upload-list--picture-card .el-upload-list__item {
    width: 60px;
    height: 60px;

}

.el-upload--picture-card {
    width: 60px;
    height: 60px;
    line-height: 60px;
}

a {
    color: #409EFF;
    text-decoration: none;
}
.el-form-item{width:345px}
</style>

</html>